package com.winit.openapi.mms.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.winit.common.spi.context.CommandContext;
import com.winit.erp.spi.bpartner.BpartnerService;
import com.winit.erp.spi.bpartner.command.BpartnerCommand;
import com.winit.erp.spi.bpartner.vo.Bpartner;
import com.winit.mms.spi.category.CategoryService;
import com.winit.mms.spi.category.vo.Category;
import com.winit.mms.spi.command.BatchImportGoodsCommand;
import com.winit.mms.spi.exception.AttributeException;
import com.winit.mms.spi.goods.GoodsService;
import com.winit.mms.spi.goods.vo.Goods;
import com.winit.openapi.constants.ApiConstant;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.mms.vo.ExceptionMessage;
import com.winit.openapi.mms.vo.GoodsVo;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.ValidateUtil;

/**
 * 
 *  商品服务controller
 * @version 
 * <pre>
 * Author	Version		Date		Changes
 * hao.gong 	1.0  		2015年5月19日 	Created
 *
 * </pre>
 * @since 1.
 */
@Controller
@RequestMapping(value = "/mms/goods")
public class GoodsController extends BaseController {
    
    /**
     * 商品服务
     */
    @Resource
    GoodsService goodsService;
    
    /**
     * 万邑通分类服务 
     */
    @Resource
    CategoryService categoryService;
    
    /**
     * 合作伙伴服务
     */
    @Resource
    BpartnerService bpartnerService;
    
    
    /**
     * 创建商品-支持批量创建
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value="/create")
    public String createGoods(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
        /*
         * <pre>1、获取请求参数</pre></br>
         */
        Object obj = requestMsg.getData();
        
        List<GoodsVo> lstGoods = new ArrayList<GoodsVo>(); 
        List<ExceptionMessage> error = new ArrayList<ExceptionMessage>();
        int successCount = 0;
        int failCount = 0;
        if (obj instanceof JSONArray) {
            JSONArray arr = (JSONArray) obj;
            for (int i = 0; i < arr.size(); i++) {
                JSONObject json = arr.getJSONObject(i);
                try {
                    // 校验参数
                    validData(json); 
                    
                    GoodsVo good = buildParams(json);
                    lstGoods.add(good);
                } catch (ApiException e) {
                    ExceptionMessage objError_ex = new ExceptionMessage();
                    objError_ex.setCode(e.getErrorCode());
                    objError_ex.setMessage(e.getErrorMsg());
                    objError_ex.setLine(i+1);
                    error.add(objError_ex);
                }
            }
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        if (error.size() <= 0) {
            BatchImportGoodsCommand command=new BatchImportGoodsCommand();
            List<Goods> goodsList = new ArrayList<Goods>();
            for (GoodsVo goodsVo : lstGoods) {
                goodsList.add(this.getGoodCommand(goodsVo));
            }
            if (error.size() <= 0) {
                try {
                    command.setGoodsList(goodsList);
                    goodsService.batchImportGoods(command);
                    successCount=goodsList.size();
                }catch (AttributeException e) {
                    successCount=0;
                    ExceptionMessage objError_ex=new ExceptionMessage();
                    objError_ex.setCode(e.getErrorCode());
                    objError_ex.setLine(e.getLine());
                    objError_ex.setMessage(e.getErrorMsg());
                    error.add(objError_ex);
                }catch (Exception e) {
                    throw new ApiException(ErrorCode.SYSTEM_ERROR);
                }
            }
        }
       //<pre>3、处理构建查询结果</pre></br>
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("successCount", successCount);
        data.put("failedCount", failCount);
        data.put("errorMessage", error);
        responseMsg.setData(data);

        return SUCCESS;
    }
    
    /**
     * 构建service command对象
     * @param goodsVo
     * @return
     */
    private Goods getGoodCommand(GoodsVo goodsVo)throws ApiException{
        Goods obj = new Goods();
        
        /**
         * 来源为api
         */
        obj.setSource(ApiConstant.SET_SOURCE);
        
        /**
         * 商品代码
         * code
         */
        obj.setGoodsCode(goodsVo.getCode());
        
        /**
         * 商品英文名称
         * eName
         */
        obj.setEnName(goodsVo.geteName());
        
        /**
         * 商品中文名称
         * nName
         */
        obj.setCnName(goodsVo.getnName());
        
        /**
         * EAN码
         * ean
         */
        obj.setEanUpc(goodsVo.getEan());
        
        /**
         * 万邑通分类代码
         * winitCategory
         */
      /*  int winitCategoryId = 0;
        if(null != goodsVo.getWinitCategory() && !"".equals(goodsVo.getWinitCategory())){
            Category objCa = categoryService.queryForSelfCode(goodsVo.getWinitCategory());
            if(null == objCa){
                throw new ApiException(ErrorCode.FIELD_FAILED_CATEGORY_CODE);
            }
            winitCategoryId = objCa.getId();
        }*/
        if(goodsVo.getWinitCategory()!=null && !goodsVo.getWinitCategory().equals("")){
            obj.setWinitCategoryId(Integer.parseInt(goodsVo.getWinitCategory()));
        }

        /**
         * 规格
         * specification
         */
        obj.setSpecification(goodsVo.getSpecification());
        
        /**
         * 单位
         * unit
         */
        obj.setUnit(goodsVo.getUnit());
        
        /**
         * 内件数
         * innerQuantity
         */
        obj.setInnerQuantity(BigDecimal.valueOf(goodsVo.getInnerQuantity()));
        
        /**
         * 图片网址
         * imageUrl
         */
        obj.setInternetSite(goodsVo.getImageUrl());
        
        /**
         * 是否有品牌(Y/N)
         * isBrand
         */
       /* if(null != goodsVo.getIsBrand() && 
                !"Y".equals(goodsVo.getIsBrand().toUpperCase()) && 
                !"N".equals(goodsVo.getIsBrand().toUpperCase())
                    ){
            throw new ApiException(ErrorCode.FIELD_FAILED_MUST_YN);
        }*/
        obj.setIsBrand(goodsVo.getIsBrand());
        
        /**
         * 品牌名称
         * brandName
         */
        obj.setBrandName(goodsVo.getBrandName());
        
        /**
         * 重量
         * weight
         */
        obj.setSellerWeight(goodsVo.getWeight());
        
        /**
         * 是否有电池(Y/N)
         * isBattery
         */
      /*  if(null != goodsVo.getIsBattery() && 
                !"Y".equals(goodsVo.getIsBattery().toUpperCase()) && 
                !"N".equals(goodsVo.getIsBattery().toUpperCase())
                    ){
            throw new ApiException(ErrorCode.FIELD_FAILED_MUST_YN);
        }*/
        obj.setIsBattery(goodsVo.getIsBattery());
        
        
        /**
         * 长
         * length
         */
        obj.setSellerLength(goodsVo.getLength());
        
        /**
         * 宽
         * width
         */
        obj.setSellerWidth(goodsVo.getWidth());
        
        /**
         * 高
         * height
         */
        obj.setSellerHeight(goodsVo.getHeight());
        
        /**
         * 体积
         * volume
         */
        obj.setSellerVolume(goodsVo.getVolume());
        
        
        CommandContext ctx = CommandContext.getContext();
        /**
         * 组织机构
         */
        obj.setOrgId(Long.valueOf(ctx.getOrgId().intValue()));
        
        /**
         * 合作伙伴ID
         */
        Long pId = Long.valueOf(Integer.parseInt(ctx.getUserId()));
        obj.setWinitPartnerId(pId);
        
        
        //查询合作伙伴信息
        BpartnerCommand bpartner = new BpartnerCommand();
        bpartner.setcBpartnerId(pId);
        Bpartner objBpartner = bpartnerService.queryBpartnerById(bpartner);
        
        /**
         * 合作伙伴代码
         */
        obj.setWinitParterCode(objBpartner.getValue());
        
        /**
         * 合作伙伴名称1
         */
        obj.setWinitParterName1(objBpartner.getName());
        
        /**
         * 合作伙伴名称2
         */
        obj.setWinitParterName2(objBpartner.getName2());
        
        /**
         * 内件单位
         */
        obj.setInnerUnit(goodsVo.getInnerUnit());
        
        /**
         * 原产国
         */
        obj.setOriginCountryCode(goodsVo.getOriginCountryCode());
       
        
        return obj;
    }
    
    /**
     * 构建请求参数
     * @param json
     * @return
     */
    private GoodsVo buildParams(JSONObject json){
        GoodsVo objGood = new GoodsVo();
        
        /**
         * 商品代码
         * code
         */
        if (json.containsKey("code")) {
            objGood.setCode(json.getString("code").trim());
        }
        
        /**
         * 商品英文名称
         * eName
         */
        if (json.containsKey("eName")) {
            objGood.seteName(json.getString("eName").trim());
        }
        
        /**
         * 商品中文名称
         * nName
         */
        if (json.containsKey("nName")) {
            objGood.setnName(json.getString("nName").trim());
        }
        
        /**
         * EAN码
         * ean
         */
        if (json.containsKey("ean")) {
            objGood.setEan(json.getString("ean").trim());
        }
        
        /**
         * 万邑通分类代码
         * winitCategory
         */
        if (json.containsKey("winitCategory")) {
            objGood.setWinitCategory(json.getString("winitCategory").trim());
        }

        /**
         * 规格
         * specification
         */
        if (json.containsKey("specification")) {
            objGood.setSpecification(json.getString("specification").trim());
        }
        
        /**
         * 单位
         * unit
         */
        if (json.containsKey("unit")) {
            objGood.setUnit(json.getString("unit").trim());
        }
        
        /**
         * 单位
         * innerQuantity
         */
        if (json.containsKey("innerQuantity")) {
            objGood.setInnerQuantity(Integer.valueOf(json.getString("innerQuantity").trim()));
        }
        
        /**
         * 图片网址
         * imageUrl
         */
        if (json.containsKey("imageUrl")) {
            objGood.setImageUrl(json.getString("imageUrl").trim());
        }
        
        /**
         * 是否有品牌(Y/N)
         * isBrand
         */
        if (json.containsKey("isBrand")) {
            objGood.setIsBrand(json.getString("isBrand").trim().toUpperCase());
        }
        
        /**
         * 品牌名称
         * brandName
         */
        if (json.containsKey("brandName")) {
            objGood.setBrandName(json.getString("brandName").trim());
        }
        
        /**
         * 重量
         * weight
         */
        if (json.containsKey("weight")) {
            BigDecimal bWeight = new BigDecimal(json.getString("weight").trim());
            objGood.setWeight(bWeight);
        }
        
        /**
         * 是否有电池(Y/N)
         * isBattery
         */
        if (json.containsKey("isBattery")) {
            objGood.setIsBattery(json.getString("isBattery").trim().toUpperCase());
        }
        
        /**
         * 长
         * length
         */
        BigDecimal bLength=BigDecimal.ZERO;
        if (json.containsKey("length")) {
            bLength = new BigDecimal(json.getString("length").trim());
            objGood.setLength(bLength);
        }
        
        /**
         * 宽
         * width
         */
        BigDecimal bWidth=BigDecimal.ZERO;
        if (json.containsKey("width")) {
            bWidth = new BigDecimal(json.getString("width").trim());
            objGood.setWidth(bWidth);
        }
        
        /**
         * 高
         * height
         */
        BigDecimal bHeight=BigDecimal.ZERO;
        if (json.containsKey("height")) {
            bHeight = new BigDecimal(json.getString("height").trim());
            objGood.setHeight(bHeight);
        }
        
        objGood.setVolume(bLength.multiply(bWidth).multiply(bHeight));
       /* *//**
         * 体积
         * volume
         *//*
        if (json.containsKey("volume")) {
            BigDecimal bVolume = new BigDecimal(json.getString("volume").trim());
            objGood.setVolume(bVolume);
        }*/
        
        /**
         * 内件单位
         * innerUnit
         */
        if (json.containsKey("innerUnit")) {
            objGood.setInnerUnit(json.getString("innerUnit").trim());
        }
        
        /**
         * 原产国
         * originCountryCode
         */
        if (json.containsKey("originCountryCode")) {
            objGood.setOriginCountryCode(json.getString("originCountryCode").trim());
        }
        
        return objGood;
    }
    
    /**
     * 参数校验
     * @param json
     */
    private void validData(JSONObject json){
        /**
         * 商品代码
         * code
         */
        ValidateUtil.validMaxLength(json, "code","产品编码", 20);
//        ValidateUtil.validByRegex(json, "code", "^[a-zA-Z0-9]+$","产品编码");
        /**
         * 商品英文名称
         * eName
         */
        ValidateUtil.validMaxLength(json, "eName","英文名称", 100);
        ValidateUtil.validNotNull(json, "eName","英文名称");
//        ValidateUtil.validByRegex(json, "eName", "^[a-zA-Z0-9]+$","英文名称");
        /**
         * 商品中文名称
         * nName
         */
        ValidateUtil.validMaxLength(json, "nName","中文名称",100);
        
        
        /**
         * EAN码
         * ean
         */
        ValidateUtil.validMaxLength(json, "ean","EAN码", 40);
        
        /**
         * 万邑通分类代码
         * winitCategory
         */
        ValidateUtil.validMaxLength(json, "winitCategory","万邑通分类代码", 40);

        /**
         * 规格
         * specification
         */
        ValidateUtil.validMaxLength(json, "specification","规格", 40);
        
        /**
         * 单位
         * unit
         */
        ValidateUtil.validMaxLength(json, "unit","单位", 50);
        ValidateUtil.validNotNull(json, "unit","单位");
        
        /**
         * 单位
         * innerQuantity
         */
        ValidateUtil.validMaxLength(json, "innerQuantity","内件数", 10);
        ValidateUtil.validNotNull(json, "innerQuantity","内件数");
        ValidateUtil.validInteger(json, "innerQuantity","内件数");
        
        /**
         * 图片网址
         * imageUrl
         */
        ValidateUtil.validMaxLength(json, "imageUrl","图片网址", 280);
        ValidateUtil.validNotNull(json, "imageUrl","图片网址");
        /**
         * 是否有品牌(Y/N)
         * isBrand
         */
        ValidateUtil.validMaxLength(json, "isBrand", "是否有品牌",1);
        
        /**
         * 品牌名称
         * brandName
         */
        ValidateUtil.validMaxLength(json, "brandName","品牌名称", 100);
        
        /**
         * 重量
         * weight
         */
        ValidateUtil.validMaxLength(json, "weight","重量", 10);
        ValidateUtil.validNotNull(json, "weight","重量");
        
        /**
         * 是否有电池(Y/N)
         * isBattery
         */
        ValidateUtil.validMaxLength(json, "isBattery", "是否有电池",1);
        ValidateUtil.validNotNull(json, "isBattery", "是否有电池");
        
        /**
         * 长
         * length
         */
        ValidateUtil.validMaxLength(json, "length","长", 10);
        ValidateUtil.validNotNull(json, "length","长");
        
        /**
         * 宽
         * width
         */
        ValidateUtil.validMaxLength(json, "width","宽", 10);
        ValidateUtil.validNotNull(json, "width","宽");
        
        /**
         * 高
         * height
         */
        ValidateUtil.validMaxLength(json, "height","高", 10);
        ValidateUtil.validNotNull(json, "height","高");
        
        /**
         * 体积
         * volume
         */
      /*  ValidateUtil.validMaxLength(json, "volume","体积", 10);*/
        //ValidateUtil.validNotNull(json, "volume", "体积");
        ValidateUtil.validBigDecimal(json, "volume", "体积", true);
        
        /**
         * 内件单位
         * unit
         */
        ValidateUtil.validMaxLength(json, "innerUnit","内件单位", 50);
        ValidateUtil.validNotNull(json, "innerUnit","内件单位");
        
        /**
         * 原产国
         * originCountryCode
         */
        ValidateUtil.validMaxLength(json, "originCountryCode","原产国代码", 2);
        ValidateUtil.validNotNull(json, "originCountryCode","原产国代码");
        
        if(json.containsKey("winitCategory")){
            String WinitCategory = json.getString("winitCategory");
            if(null != WinitCategory && !"".equals(WinitCategory)){
                Category objCa = categoryService.queryForSelfCode(WinitCategory);
                if(null == objCa){
                    throw new ApiException(ErrorCode.FIELD_FAILED_CATEGORY_CODE,"万邑通分类代码");
                }
                json.put("winitCategory", objCa.getId());
            }
        }
        /**
         * 是否有品牌(Y/N) isBrand
         */
        if (json.containsKey("isBrand")) {
            String isBrand = json.getString("isBrand");
            if (null !=isBrand && StringUtils.isNotBlank(isBrand) && !"Y".equals(isBrand.toUpperCase())
                && !"N".equals(isBrand.toUpperCase())) {
                throw new ApiException(ErrorCode.FIELD_FAILED_MUST_YN,"是否有品牌");
            }
        }
        if (json.containsKey("isBattery")) {
            String isBattery = json.getString("isBattery");
            if (null != isBattery && StringUtils.isNotBlank(isBattery) && StringUtils.isNotBlank("") && !"Y".equals(isBattery.toUpperCase())
                && !"N".equals(isBattery.toUpperCase())) {
                throw new ApiException(ErrorCode.FIELD_FAILED_MUST_YN,"是否有电池");
            }
        }
    }

}
